/**
 * 
 */
package com.thinkgsp.jxc.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgsp.jxc.model.Emp;
import com.thinkgsp.jxc.persistence.EmpMapper;
import com.thinkgsp.jxc.service.EmpService;
import com.thinkgsp.jxc.service.ModelExistsException;
import com.thinkgsp.jxc.service.ServiceException;
import com.thinkgsp.sys.model.SysUser;
import com.thinkgsp.sys.persistence.PersistenceException;

/**
 * EmpService 的实现类
 * @author evan
 *
 */
@Service("empService")
@Transactional
public class EmpServiceImpl extends GeneralServiceImpl implements EmpService {

	@Autowired
	private EmpMapper empMapper;
	/* (non-Javadoc)
	 * @see com.thinkgsp.jxc.service.EmpService#getEmp(java.lang.Integer)
	 */
	public Emp getEmp(Integer empId) {
		return empMapper.getEmp(empId);
	}

	/* (non-Javadoc)
	 * @see com.thinkgsp.jxc.service.EmpService#getAllEmp()
	 */
	public List<Emp> getAllEmp() {
		return empMapper.getAllEmp();
	}

	/* (non-Javadoc)
	 * @see com.thinkgsp.jxc.service.EmpService#getEmpByDeptId(java.lang.Integer)
	 */
	public List<Emp> getEmpByDeptId(Integer deptId) {
		return empMapper.getEmpByDeptId(deptId);
	}

	/* (non-Javadoc)
	 * @see com.thinkgsp.jxc.service.EmpService#saveEmp(com.thinkgsp.jxc.model.Emp)
	 */
	public void saveEmp(Emp emp) throws ModelExistsException,PersistenceException {
		try {
			if(emp.getEmpId() == null || emp.getEmpId().intValue() == 0) {
				empMapper.insertEmp(emp);
			} else {
				int cnt = empMapper.updateEmp(emp);
				if(cnt == 0) {
					throw new PersistenceException("职员:'" + emp.getEmpName() + "' 更新失败。");	
				}
			}
		} catch(PersistenceException e) {
			throw e;
		} catch(DuplicateKeyException e) {
			log.warn(e.getMessage());
		} catch(Exception e) {
			log.error(e);
			throw new PersistenceException("职员:'" + emp.getEmpName() + "' 保存失败。");			
		}

	}

	/* (non-Javadoc)
	 * @see com.thinkgsp.jxc.service.EmpService#deleteEmp(java.lang.Integer)
	 */
	public void deleteEmp(Integer empId) throws PersistenceException {
		int cnt = empMapper.deleteEmp(empId);
		if(cnt == 0) {
			log.warn("Delete emp by id :'" + empId + "' faild.");
			throw new PersistenceException("职员:'" + empId + "' 删除失败。");			
		}
	}

	public void setEmpMapper(EmpMapper empMapper) {
		this.empMapper = empMapper;
	}

	public Emp getLoginEmp() throws ServiceException {
		SysUser user = getCurrentUser();
		Integer empId = user.getEmpId();
		if(empId == null) {
			throw new ServiceException("您的账户未关联职员。");
		}
		return empMapper.getEmp(empId);
	}

}
